﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Http.Filters;
using System.Net.Http;

using ERPStore.Extensions;

namespace ERPStore.Web.Controllers.ActionFilters
{
	public class LogExceptionFilter : ExceptionFilterAttribute
	{
		public override void OnException(HttpActionExecutedContext actionExecutedContext)
		{
			if (actionExecutedContext.Exception == null)
			{
				return;
			}
			var logger = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Logging.ILogger>();
			var ex = actionExecutedContext.Exception;
			var body = actionExecutedContext.Request.Content.ReadAsStringAsync().Result;
			ex.Data.Add("Request.Body", body);
			if (actionExecutedContext.Response != null)
			{
				ex.Data.Add("Response.ReasonPhrase", actionExecutedContext.Response.ReasonPhrase);
			}

			logger.Error(ex);

			//var response = new HttpResponseMessage();
			//response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
			//response.ReasonPhrase = actionExecutedContext.Exception.Message.Replace(System.Environment.NewLine, string.Empty);
			//response.Content = new StringContent(actionExecutedContext.Exception.ToString());
			//actionExecutedContext.Response = response;
		}
	}
}
